package com.heima.search.service.impl;

import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.search.service.ApSearchHistroyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ApSearchHistroyServiceImpl implements ApSearchHistroyService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String PREFIX= "leadnews:search:";

    @Override
    public void saveHistory(String searchWords, String equipId) {
        //1234
        Integer userId = UserThreadLocalUtils.getUserId();
        String key = buildKey(userId, equipId);
        redisTemplate.boundZSetOps(key).incrementScore(searchWords, 1);
        // 另一个开发人员，向redis写入的是文章的缓存 key:  文章的id    value：文章的数据
        // 有可能出现，文章的id 和 用户的id 相等的时候，就互相覆盖！
        // 因此需要给key添加前缀
        // 前缀规则： 部门:项目:模块:key
        // dev:leadnews:search:1234
        // dev:leadnews:article:1234
    }

    @Override
    public List<String> getHistory(Integer userId, String equipId, String words){
        String key = buildKey(userId, equipId);
        Set<String> values = redisTemplate.boundZSetOps(key).reverseRangeByScore(0, Double.MAX_VALUE);
        if(CollectionUtils.isEmpty(values)){
            return new ArrayList<>();
        }
        if(StringUtils.isEmpty(words)){
            return new ArrayList<>(values);
        }
        return values.stream().filter(value->value.indexOf(words)>=0).collect(Collectors.toList());
    }

    private String buildKey(Integer userId, String equipId){
        String key = "";
        if(userId == null || userId <= 0){
            key = equipId;
        }else{
            key = ""+userId;
        }
        return PREFIX + key;
    }



}
